import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:math';
import 'GlobalSeer.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';

late BluetoothDevice device;


class MyBlues{

  void startScan() {

    // StreamSubscription<BluetoothDiscoveryResult>? _discoveryStreamSubscription = FlutterBluetoothSerial.instance.startDiscovery().listen((r) {});
    // _discoveryStreamSubscription?.onDone(() {});
    FlutterBluetoothSerial.instance.getBondedDevices().then((List<BluetoothDevice> bondedDevices) {
      print("bondedDevices:"+bondedDevices.toString());
      List<Widget> items=[];
      for(BluetoothDevice item in bondedDevices){
        items.add(ListTile(
          title:Text("name:"+item.name.toString()) ,
          onTap: (){
            GlobalSeer.dispatchEvent("onDialogDone",item);
            Get.back();
          },
        ));
      }
      Get.defaultDialog(
        title: "BLES",
        content: Column(children: items,),
      );
    });
  }

  void connectDevice(BluetoothDevice device) async{
    print("connectDevice");
    try {
      BluetoothConnection connection = await BluetoothConnection.toAddress(device.address);
      print('Connected to the device');



      connection.input?.listen((Uint8List data) {
        //print('Data incoming: ${ascii.decode(data)}');
        print('Data incoming: ${utf8.decode(data)}');

        if (ascii.decode(data).contains('!!')) {
          connection.finish(); // Closing connection
          print('Disconnecting by local host');
        }
      }).onDone(() {
        print('Disconnected by remote request');
      });

      Timer(const Duration(seconds: 3), () {
        connection.output.add(utf8.encode("king456"));
      });



    } catch (exception) {
      print('Cannot connect, exception occured');
    }
  }

}

main(){
  runApp(TheApp());
}

class TheApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(home: MyHome(),);
  }
}

class MyHome extends StatelessWidget{

  MyBlues blues=MyBlues();

  @override
  Widget build(BuildContext context){

    GlobalSeer.addEventListener("onDialogDone", (BluetoothDevice device){
      print("device.id:"+device.toString());
      blues.connectDevice(device);
    });

    return Scaffold(
      appBar: AppBar(title:const Text("BLE"),centerTitle: true,backgroundColor: Colors.purple,),
      body:Center(
        child:Column(
          children:[
            const SizedBox(height: 50,),
            ElevatedButton(onPressed: (){
              blues.startScan();
            }, child: const Text("SCAN")),
            const SizedBox(height: 50,),
            Text("deciceName:"),
            const SizedBox(height: 50,),
            ElevatedButton(onPressed: (){
              GlobalSeer.removeEventListener("onDialogDone");
            }, child: const Text("Remove")),
          ],
        ) ,
      ),

    );
  }

}

